#会突然卡死
from collections import namedtuple

from tornado.tcpserver import TCPServer
from tornado.iostream import StreamClosedError
from tornado.ioloop import IOLoop
import time
Client = namedtuple('Client', ['stream', 'address'])

a=0
t1=t2=time.time()
class ChatServer(TCPServer):
    clients = set()

    async def handle_stream(self, stream, address):
        global a,t2,t1
        # print("A new user has entered the chat room.", address)
        client = Client(stream, address)
        self.clients.add(client)
        # print("connection num is:", len(self.clients))
        while True:
            try:
                data = await stream.read_until(b'\n')
                # print("User said:", data[:-1], client.address)
                a+=1
                if a%10000==0:
                    t2=time.time()
                    print(t2-t1,a)
                    t1=t2
                for conn in self.clients:
                    await conn.stream.write(data)
            except StreamClosedError:
                # print("A user has left the chat room.", client.address)
                self.clients.remove(client)
                break


if __name__ == '__main__':
    print("Server start ......")
    server = ChatServer()
    server.listen(12347,'127.0.0.1')
    IOLoop.instance().start()